package com.imooc.bilibili.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.*;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * ProjectName imooc-bilibili
 * 对称加密算法
 * @author xieyucan
 * <br>CreateDate 2022/10/21 16:49
 */
public class AESUtil {

    private static final String KEY_ALGORITHM="AES";
    private static final char[] HEX_CHAR={'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    private final Cipher decryptCipher;
    private final Cipher encryptCipher;
    private final String seed;

    public AESUtil(String seed) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
        this.seed=seed;
        decryptCipher=Cipher.getInstance(KEY_ALGORITHM);
        encryptCipher=Cipher.getInstance(KEY_ALGORITHM);
        decryptCipher.init(Cipher.DECRYPT_MODE, this.getSecretKey());
        encryptCipher.init(Cipher.ENCRYPT_MODE, this.getSecretKey());
    }

    public String decrypt(String content) throws BadPaddingException, IllegalBlockSizeException {
        byte[] bytes = Base64.decodeBase64(content);
        byte[] doFinal = decryptCipher.doFinal(bytes);
        return new String(doFinal, StandardCharsets.UTF_8);
    }

    public String encrypt(String content) throws Exception {
        byte[] result = encryptCipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
        return org.apache.tomcat.util.codec.binary.Base64.encodeBase64String(result);
    }

    public SecretKey getSecretKey() throws NoSuchAlgorithmException {
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(seed.getBytes());
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
        keyGenerator.init(128,random);
        return keyGenerator.generateKey();
    }

}
